

import { sys } from "cc";
import Singleton from "../Singleton";
import { utils } from "../Utils";

export default class HttpManager extends Singleton<HttpManager> {
    private reconnectCount = 5
    private isRequesting = false
    private token = ""
    private baseUrl = ""
    private testBody = null
    private httpReq = null
    
    get getIsRequesting(){
        return this.isRequesting;
    } 
    
    public init(url,httpReq,testBody){
        this.baseUrl = url
        this.testBody = testBody
        this.httpReq = httpReq
    }
    /**
     * 发送http请求
     * @param netid  请求id 
     * @param params 请求参数  json格式
     * @param callback 回调
     * @param showLoad 是否显示转圈圈的动画  默认显示 true
     */
    public req(netId, callback, params = null ,showLoad = true){
        if(this.testBody[netId] != null){
            callback(this.testBody[netId])
            return
        }
        let reqData = this.httpReq[netId]
        let url = this.baseUrl + reqData.path
        let reqType = reqData.reqType
        
        let paramStr = ""
        if(reqType == "GET"){
            if(params && typeof(params) == "object"){
                paramStr = this.setGetParam(params)
            }
            this.get(url + paramStr, callback,showLoad)
        }else{
            if(params && typeof(params) == "object"){
                paramStr = this.setPostParam(params)
            }
            this.post(url , paramStr, callback,showLoad)
        }
    }

    public setToken(token){
        this.token = token
        console.log("token 1 ", this.token )
    }

    private setGetParam(params): string{
        let ret = ""
        for (const key in params) {
            if(ret == ""){
                ret = "?" + key + "=" + params[key]
            }else{
                ret = ret + "&" + key + "=" + params[key]
            }
        }
        return ret
    }

    private setPostParam(params): string{
        let ret = JSON.stringify(params)
        return ret
    }
    
    
    private get(url:string, callback,showLoad) {
        let idx = 0
        let isGot = false
        let that = this
        //if(showLoad)load.showLoad()
        let requesting = ()=>{
            if(isGot){
                return
            }
            that.isRequesting = showLoad
            console.log(url)
            var xhr = new XMLHttpRequest()
            xhr.timeout = 5000;
            var requestURL = url 

            xhr.open("GET", requestURL, true);
            xhr.setRequestHeader("Accept", "application/json");   
            console.log("token 2 ", this.token )
            xhr.setRequestHeader("Authorization", this.token);         
            xhr.onreadystatechange = function () {
                if(xhr.readyState != 4) return;
                if (xhr.status >= 200 && xhr.status < 400) {
                    try {
                        var ret = xhr.responseText;
                        console.log(ret)
                        if (callback !== null) {
                            isGot = true
                            that.isRequesting = false
                           // //if(showLoad)load.hideLoad()
                            
                            let json = JSON.parse(ret)
                            let isHeart = url.search("roomHeart")
                            if(json.code > 0){
                                if(isHeart == -1){
                                    // msgNode.show(json.msg)
                                    console.error(json.msg)
                                }
                            }else{
                                callback(json);
                            }
                        }
                        return;
                    } catch (e) {
                        console.error("GET 网络信息数据解析 " + requestURL)
                    }
                } else {
                    console.error("GET 网络信息获取失败 " + requestURL)
                }
            };
            
            xhr.send();
            idx = idx + 1
            if(idx == this.reconnectCount + 1){
                that.isRequesting = false
                //if(showLoad)load.hideLoad()
            }
            return xhr;
        }
        for(let tIdx = 0; tIdx < this.reconnectCount; tIdx++){
            // utils.delayCall(5*(tIdx + 1),()=>{
            //     requesting()
            // })
        }
        requesting()
    }

    private post(url:string, param, callback,showLoad) {
        let idx = 0
        let isGot = false
        let that = this
        //if(showLoad)load.showLoad()
        let requesting = ()=>{
            if(isGot){
                return
            }
            console.log(url,param)
            that.isRequesting = showLoad
            var xhr = new XMLHttpRequest()
            xhr.timeout = 5000;
            var requestURL = url 

            // if (sys.isNative) {
            //     xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
            // }
            xhr.open("POST", requestURL);
            
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", "application/json");
            console.log("token 3 ", this.token )
            xhr.setRequestHeader("Authorization", this.token);    

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                    try {
                        var ret = xhr.responseText;
                        console.log(ret)
                        if (callback !== null) {
                            isGot = true
                            that.isRequesting = false
                            //if(showLoad)load.hideLoad()

                            let json = JSON.parse(ret)
                            let isPayBack = url.search("notifyCallback")
                            if(json.code > 0){
                                if(isPayBack == -1){
                                    // msgNode.show(json.msg)
                                    console.error(json.msg)
                                }
                            }else{
                                callback(json);
                            }
                        }
                        return;
                    } catch (e) {
                        console.error(`Post 网络信息数据解析 ${url} ${e}`)
                        // callback(e);
                    }
                }
                else {
                    if(xhr.readyState==4 &&  xhr.status == 0){
                        
                    }
                    //callback(xhr.readyState + ":" + xhr.status);
                    console.error("Post 网络信息状态 " + xhr.readyState + ":" + xhr.status)
                }
            };
            idx = idx + 1
            if(idx == this.reconnectCount + 1){
                that.isRequesting = false
                //if(showLoad)load.hideLoad()
            }
            xhr.send(param);
            return xhr;
        }
        

        for(let tIdx = 0; tIdx < this.reconnectCount; tIdx++){
            // utils.delayCall(5*(tIdx + 1),()=>{
            //     requesting()
            // })
        }
        requesting()
    }

    download(url, path, params, callback) {
        var xhr = new XMLHttpRequest()//loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if (params) {
            requestURL = requestURL + "?" + params;
        }

        xhr.responseType = "arraybuffer";
        xhr.open("GET", requestURL, true);
        if (sys.isNative) {
            xhr.setRequestHeader("Accept", "text/html");
            xhr.setRequestHeader("Accept-Charset", "utf-8");
            xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                var buffer = xhr.response;
                var dataview = new DataView(buffer);
                var ints = new Uint8Array(buffer.byteLength);
                for (var i = 0; i < ints.length; i++) {
                    ints[i] = dataview.getUint8(i);
                }
                callback(null, ints);
            }
            else {
                callback(xhr.readyState + ":" + xhr.status, null);
            }
        };
        xhr.send();
        return xhr;
    }
}